package com.rpframework.module.common.spring;

import com.rpframework.core.json.*;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 控制层抛出异常处理组件Aspect切面Bean
 *
 * @author 刘兴
 */
@Aspect
public class ControllerExceptionAop {
    public final Logger log = LoggerFactory.getLogger(getClass());
    /**
     * JSON操作对象
     */
    private JsonResp json = new JsonResp();

    /**
     * 配置切入点,该方法无方法体,主要为方便同类中其他方法使用此处配置的切入点
     */
    @Pointcut("execution(public com.rpframework.core.json.JsonResp *..controller..*Controller.*(..))")
    public void aspectEx() {
    }

    /**
     * 配置抛出异常后通知,使用在方法aspect()上注册的切入点
     *
     * @param ex 异常对象
     */
    @AfterThrowing(value = "aspectEx()", throwing = "ex")
    public void afterThrowingAdvice(JoinPoint joinPoint, Exception ex) {
        JsonResp jsonResp = null;
        if (ex instanceof JsonException) {
            JsonException codeException = (JsonException) ex;
            jsonResp = codeException.getJsonResp();
        }
        log.error("----->controller", ex);
        HttpServletResponse response = ServletThreadLocal.getResponse();
        PrintWriter writer;
        try {
            writer = response.getWriter();
            String msg = null;
            // 参数不合法
            if (ex instanceof ParameterException) {
                json.setCode(JsonCodeEnum.PARAMETER_INVALID);
                msg = ex.getMessage();
                json.setMsg(msg);
            } else if (ex instanceof EmptyException) {
                json.empty(ex.getMessage());
            } else if (ex instanceof JsonException) {
                JsonException codeException = (JsonException) ex;
                json = codeException.getJsonResp();
            } else {
                json.setCode(JsonCodeEnum.FAIL);
                json.setMsg("服务器出错了");
            }
            writer.append(json.toJson());
            writer.close();
        } catch (IOException e) {
            log.error("获取PrintWriter失败", e);
        }
    }
}
